package com.arithmetic;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

/*字符串的所有组合*/

public class StringRandomPrint {

	public static void main(String[] args) {
		List<String> list = getResultList("abc");
		System.out.println(list);
	}

	public static List<String> getResultList(String s) {
		HashSet<String> set = new HashSet<String>();
		traverseCharArray(s.toCharArray(), set);
		List<String> list = new LinkedList<String>(set);
		Collections.sort(list, new Comparator<String>() {
			public int compare(String o1, String o2) {
				if (o1.length() == o2.length()) {
					return o1.compareToIgnoreCase(o2);
				} else {
					return o1.length() - o2.length();
				}
			}
		});
		return list;
	}

	public static void traverseCharArray(char[] chars, HashSet<String> set) {
		for (int i = 0; i < chars.length; i++) {
			recursionMerge(chars[i], getOther(chars, i), set);
		}
	}

	public static Set<String> recursionMerge(char c, char[] chars,
			HashSet<String> set) {
		Set<String> merges = new HashSet<String>();
		String merge = merge(c + "", new String(chars));
		merges.add(merge);
		set.add(merge);

		for (int i = 0; i < chars.length; i++) {
			Set<String> mergeSet = recursionMerge(chars[i], getOther(chars, i),
					set);
			for (String str : mergeSet) {
				String merge2 = merge(c + "", str);
				set.add(merge2);
				merges.add(merge2);
			}
		}
		return merges;
	}

	public static char[] getOther(char[] c1, int index) {
		StringBuffer buffer = new StringBuffer(new String(c1));
		buffer.deleteCharAt(index);
		return buffer.toString().toCharArray();
	}

	public static String merge(String s1, String s2) {
		return s1 + s2;
	}

}
